package cn.kgc.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Spliterator;

/**
 * @author 课工场
 * @date 2023/12/5
 * @description token 创建 , 验证 ,解析工具类
 */
@Component
public class JWTUtil {

    @Value("${secret}")
    private String secret;
    @Value("${time}")
    private Integer expireTime;

    // 创建token
    public String createToken(Map<String, Object> payload) {

        HashMap<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, expireTime);

        return JWT.create()
                .withHeader(header)
                .withClaim("userInfo", payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));

    }

    // 解析token
    public Map<String, Object> getClaims(String token) {
        return JWT.decode(token).getClaim("userInfo").asMap();
    }

    // 验证token
    public Boolean verifyToken(String token) {
        JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return true;
    }


}
